<?php

namespace app\admin\controller;

use function Alipay\decrypt;
use app\inter\logic\DriverLogic;
use app\inter\logic\OrderLogic;
use app\inter\logic\PersonalLogic;
use app\inter\logic\TripLogic;
use app\inter\logic\UserLogic;
use app\admin\inter_logic\CarLogic;
use app\admin\inter_logic\DriverLogic as InterDriverLogic;
use app\inter\model\OrderCommonModel;
use my\Address;
use my\Security;
use my\Tools;
use think\Cache;
use think\Db;
use app\admin\model\RegionModel;
use think\Log;
use think\env;
use app\admin\model\AdminModel;

class InterOrder extends Base
{
    protected $limit = 10;//每页显示记录数
    public $column = array(
        'order_sn' => '订单编号',
        'start_name' => '出发地点',
        'arrive_name' => '目的地点',
        'order_status' => '订单状态',
        'user_phone' => '用户手机号',
        'order_time' => '下单时间',
        'passenger_number' => '乘客人数',
        'contact_number' => '联系手机号',
        'start_time' => '预约出发时间',
        'cancel_reason' => '取消原因',

        'dep_time' => '上车时间',
        'dest_time' => '下车时间',
        'driver_name' => '司机姓名',
        'driver_phone_number' => '司机手机号',
        'car_plate' => '车牌号',
        'car_brand' => '车辆品牌',
        'car_model' => '车辆型号',
        'color' => '颜色',
        'dis' => '起止地行程公里数',
        'journey' => '全部行程公里',


        'is_pay' => '付款状态',
        'order_price' => '订单金额',
        'unit_price' => '单价',
        'coupon_price' => '优惠金额',
        'need_price' => '实付金额',
        'pay_time' => '支付时间',
        'paytool' => '支付方式',
        'platform_price' => '平台费(包含车队收入)',
        'fleet_price' => '车队收入',
        'driver_fine_money' => '司机罚款',
        'refund_money' => '退款金额',
    );
    protected $map = array();
    protected $map_work_city = array();
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $base_condition = $this->base_condition;
        if($base_condition){
            $this->map['start_code'] = $base_condition['region_code'];
        }
        //$base_condition && $this->map['start_code'] = $base_condition['region_code'];
        $adminInfo = Db::name('admin')->field('admin_type,region')->where('admin_id', session('admin_id'))->find();
        /*
         2020.7.6 lili
         add $adminInfo['admin_type'] == 2，3, 4
        $this->map_work_city -> d.work_province d.work_city d.work_county
         */
        if($adminInfo['admin_type'] == 2){
            $result_province = $adminInfo['region'][$adminInfo['admin_type']];
            $this->map_work_city['d.work_province'] = ['in',implode(',',$result_province)];
        }elseif($adminInfo['admin_type'] == 3){

            $result_city  = array_reduce($adminInfo['region'][$adminInfo['admin_type']], 'array_merge', array());
            $this->map_work_city['d.work_city'] = ['in',implode(',',$result_city)];
        }elseif ($adminInfo['admin_type'] == 4) {//县级管理员
            $region_arr = json_decode($adminInfo['region'], true);
            if (count($region_arr['4']) > 1) {//***有两个管理区域的,出发点和到达点都在这两个区域里面，否则，只是出发点在区域里面
                if($base_condition){
                    $this->map['arrive_code'] = $base_condition['region_code'];
                }
                //$base_condition && $this->map['arrive_code'] = $base_condition['region_code'];
            }
            $result_county   = array_reduce($adminInfo['region'][$adminInfo['admin_type']], 'array_merge', array());
            $this->map_work_city['d.work_county'] = ['in',implode(',',$result_county)];
        }

        $this->map['is_del'] = 2;//显示不删除的1是2否
        // $base_condition&&$this->map['arrive_code'] = $base_condition['region_code'];
    }

    public function index()
    {
        $config['url'] = url('inter_order/table');
        $config['order_status'] = inter_order_status();
        $config['pay_type'] = pay_type();
        $config['is_pay'] = ['0' => '未支付', '1' => '已支付'];
        $config['arean'] = Db::table('inter_arean')->order('id asc')->select();

        //$fleet_list = Db::connect('db2')->table('fleet')->field('id,name')->order('id DESC')->select();
        $config['fleet_list'] = null;
        $config['is_contract'] = ['否', '是'];

        //查询省市区
        $region_model = new RegionModel();
        //查询获取省份
        $where = [
            'parent_id' => 1,
            'region_level' => 1
        ];
        $config['province'] = $region_model->getRegion($where, 'region_id,region_name');
        $this->assign($config);
        return view();
    }

    public function table()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $order_logic = new OrderLogic();
        $field = "a.*,a.order_status as status,start_address_name,end_address_name,car_plate,driver_name,driver_phone";
        $res = $order_logic->getOrderCommon($this->map, $field, true, 'a.id desc', $page, $limit);

        $count = Db::table('inter_order_common a')
            ->join(['inter_car_banci' => 'd'], 'a.banci_id=d.id', 'LEFT')
            ->join(['xm_driver_base' => 'e'], 'a.driver_id=e.driver_id', 'LEFT')
            ->join(['xm_car_info' => 'f'], 'a.car_id=f.car_id', 'LEFT')
            ->join(['inter_order_comment' => 'g'], 'g.common_id=a.id', 'LEFT')
            ->where($this->map)
            ->count();

        $whiteList = Db::name('white_list')->order('id desc')->find();

        foreach ($res as $key => $value) {
            //测试账号名单
            if (!empty($whiteList['uid_str']) && in_array($value['member_id'], explode(',', $whiteList['uid_str']))) {
                $res[$key]['user_type'] = 1;
            } else {
                $res[$key]['user_type'] = 0;
            }
            //查询司机真实手机号码
            if (!empty($value['real_phone'])) {
                $res[$key]['real_phone'] = Security::decrypt($value['real_phone']);
            } else {
                $res[$key]['real_phone'] = '-';
            }
            //类型
            if (!empty($whiteList['driver_str']) && in_array($value['driver_id'], explode(',', $whiteList['driver_str']))) {
                $res[$key]['driver_type'] = 1;
            } else {
                $res[$key]['driver_type'] = 0;
            }

            foreach ($value as $k => $v) {
                if ($k == 'order_status') {
                    $res[$key][$k] = inter_order_status()[$v];
                }
            }
        }

        $car_logic = new CarLogic();
        $driver_logic = new DriverLogic();
        $user_logic = new UserLogic();
        foreach ($res as $key => $val) {

            $order_area = Db::table('xm_region a')
                ->field('a.region_name as area_name, c.region_name as city_name, p.region_name as province_name')
                ->join(['xm_region' => 'c'], 'a.parent_id=c.region_id', 'LEFT')
                ->join(['xm_region' => 'p'], 'c.parent_id=p.region_id', 'LEFT')
                ->where('a.region_code = ' . $val['start_code'])
                ->find();

            $passenger_res = Db::table('inter_order_common')->field('passenger_number')->where(['id' => $val['id']])->find();
            $res[$key]['passenger'] = $passenger_res['passenger_number'];
            //$res[$key]['ban'] = $val['start_address_name'].'-'.$val['end_address_name'];
            $res[$key]['user_phone'] = Security::decrypt($user_logic->getUserByUid($val['member_id'], 'user_phone')['user_phone']);
            $res[$key]['driver_phone'] = Security::decrypt($val['driver_phone']) ?: '';
            $res[$key]['car_plate'] = Security::decrypt($val['car_plate']) ?: '';

            $res[$key]['area'] = $order_area['province_name'].'/'.$order_area['city_name'].'/'.$order_area['area_name'];
            $res[$key]['order_time'] = date('Y-m-d H:i:s', $val['order_time']);
            $res[$key]['start_time'] = date('Y-m-d H:i:s', $val['start_time']);

            //车队名称
            $fleet_info = Db::connect('db2')->table('fleet')->field('name')->where(['id' => $val['fleet_id']])->find();
            $res[$key]['fleet_name'] = $fleet_info['name'] ?: '';

            //是否包车
            if ($val['is_contract']) {
                $charter_car_info = Db::table('inter_charter_car')->field('model_name')->where(['id' => $val['charter_car_id']])->find();
                $res[$key]['is_contract'] = $charter_car_info['model_name'] ?: '';
            } else {
                $res[$key]['is_contract'] = '否';
            }
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'limit' => $limit,
            'count' => $count,
            'data' => $res,
        ));
    }

    //派单人员列表
    public function fleet_driver_table()
    {
        $page = input('get.page');
        $limit = input('get.limit');

        $driver_name = trim(input('get.driver_name'));
        $driver_phone = trim(input('get.driver_phone'));
        $map = [];
        $driver_name && $map['driver_name'] = $driver_name;
        $driver_phone && $map['driver_phone'] = Security::encrypt($driver_phone);

        $common_id = input('get.common_id');

        $order_logic = new OrderLogic();
        $info = $order_logic->getOrderCommonById($common_id, 'a.*,a.order_status as status,start_name,arrive_name,car_plate,driver_name,driver_phone,car_brand,car_model,color');

        $info['car_plate'] = Security::decrypt($info['car_plate']) ?: '';
        $info['journey'] = intval($info['journey']);
        $info['dis'] = intval($info['dis']);
        $info['car_brand'] = Security::decrypt($info['car_brand']) ?: '';
        $info['car_model'] = Security::decrypt($info['car_model']) ?: '';
        $info['color'] = Security::decrypt($info['color']) ?: '';

        //用户手机号
        $user_logic = new UserLogic();
        $info['user_phone'] = Security::decrypt($user_logic->getUserByUid($info['member_id'], 'user_phone')['user_phone']);
        $info['driver_phone_number'] = Security::decrypt($info['driver_phone']) ?: '';
        unset($info['driver_phone']);

        //退款订单金额
        if ($info['status'] == 25 || $info['status'] == 10) {
            $info['refund_money'] = $info['need_price'];
        }

        //司机罚款金额
        $fine_money_res = Db::table('xm_driver_wallet_record')->field('money')->where(['common_id' => $info['id'], 'record_type' => 3])->find();
        $info['driver_fine_money'] = $fine_money_res['money'];

        $res = [];
        if ($info) {
//            $allot_driver = $this->findAllotFleetDriver($order_logic, $info,$page,$limit);
            $res = $this->findAllotFleetDriver($order_logic, $info, $page, $limit, $map);
        }

        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'limit' => $limit,
            'count' => $res['count'],
            'data' => $res['driver_info'],
        ));
    }

    private function findAllotFleetDriver($order_logic, $info, $page, $limit, $map)
    {
        $driver_logic = new DriverLogic();
        $inter_driver_logic = new InterDriverLogic();
        $start_local = explode(',', $info['start_local']);
//		$map_driver['is_goon']=array(array('eq',2),array('eq',3),'OR');
        $map_driver['driver_status'] = ['in','0,1,2,3,4'];
        $map_driver['auth_status'] = 1;
        $map_driver['forbid'] = 2;
        $map_driver['car_default'] = 1;
        $map_driver['c.valid_time'] = ['>=', time()];   //判断行驶证是否过期
//        $map_driver['auth_type'] = 1; //司机认证类型 1 专车 2 出租车(城际) 3城际拼车  5 私人运营车辆
        $map_driver['driver_type'] = 2;

        $whereOr = [];
        if($info['driver_id']) {
            $whereOr['a.driver_id'] = $info['driver_id'];
        }

        if (!empty($map)) {
            $map['driver_name'] && $map_driver['driver_name'] = ['like', '%' . $map['driver_name'] . '%'];
            $map['driver_phone'] && $map_driver['driver_phone'] = $map['driver_phone'];
        }

        //归属车队
        $map_driver['b.franchisee_type'] = 5; //1分公司 2区县代理 3驿站 4快车租赁公司 5城际车队
        $map_driver['b.franchisee_id'] = $info['fleet_id'];

        $driver_info = $driver_logic->getCarList($map_driver, 'a.car_id,a.driver_id,car_plate,seats,driver_name,b.franchisee_type,b.franchisee_id,b.driver_phone', $flag = true, $order = 'seats desc,a.car_id desc', $page, $limit, $whereOr);

        if(!empty($whereOr)) {
            $count = Db::table('xm_car_info a')->join(['xm_driver_base' => 'b'], 'b.driver_id=a.driver_id', 'LEFT')->join(['xm_driver_info' => 'c'], 'c.driver_id = b.driver_id', 'LEFT')
                ->where($map_driver)->whereOr($whereOr)->count();
        } else {
            $count = Db::table('xm_car_info a')->join(['xm_driver_base' => 'b'], 'b.driver_id=a.driver_id', 'LEFT')->join(['xm_driver_info' => 'c'], 'c.driver_id = b.driver_id', 'LEFT')
                ->where($map_driver)->count();
        }

        foreach ($driver_info as $key => $value) {
            $driver_info[$key]['car_plate'] = Security::decrypt($value['car_plate']);
        }

        /******************************获取司机位置（mongo）***************************/
        $map_driver_mongo['driverId'] = array('in', array_column($driver_info, 'a.driver_id'));
        $map_driver_mongo['authType'] = 3;
        $driver_coordinate = Db::connect(config('mongodb'))->table('live_driver_location')->where($map_driver_mongo)->field('driverId,location')->select();

        $driver_coordinate = array_column($driver_coordinate, 'location', 'driverId');
        /******************************获取司机位置（mongo）***************************/
        $map_order_common['order_status'] = 35;//已分配
        foreach ($driver_info as $key => $val) {
            $map_order_common['a.driver_id'] = $val['driver_id'];

            $order_logic = new OrderLogic();
            $common_id_arr = $order_logic->getOrderCommon($map_order_common, 'a.id,a.banci_id');

            $order_count = 0;
            $flag = false;
            foreach ($common_id_arr as $value) {
                //$order_count += $order_logic->orderCountByCommonId($value['id']);
                $order_count_res = Db::table('inter_order_common')->field('passenger_number')->where(['id' => $value['id']])->find();
                $order_count += $order_count_res['passenger_number'];
                //司机有分派订单，但是路线不一样，则不能被派单  2019-1-30注释  -张卫
                // if($order_count && $value['banci_id']!=$info['banci_id']){
                // 	unset($driver_info[$key]);$flag = true;
                // 	break;
                // }

            }
            /*************判断有订单的司机班线和本订单是否相同***********************/
            if ($flag) {
                continue;
            }
            /*************判断有订单的司机班线和本订单是否相同***********************/
            /*************判断司机分配的乘客是否已满***********************/

            //不限制 不同时间段 座位数
//			if($order_count>=$val['seats']){
//				unset($driver_info[$key]);
//				continue;
//			}

            /*************判断司机分配的乘客是否已满***********************/

            $work_area = $inter_driver_logic->getDriverByDid($val['driver_id'], 'a.driver_id');
            $driver_info[$key]['work_area'] = $work_area['city'] . $work_area['county'];
            if ($info['order_status'] == 30) {
                $distance[$key] = Address::GetDistance($start_local[1], $start_local[0],
                    $driver_coordinate[$val['driver']]['coordinates'][1], $driver_coordinate[$val['driver']]['coordinates'][0]) ?: 0;
            }

            $driver_info[$key]['allot_count'] = $order_count;

            // 已占座/总座位数
            $driver_info[$key]['seat_num'] = $order_count . '/' . $val['seats'];
            $driver_info[$key]['driver_phone'] = Security::decrypt($val['driver_phone']);

        }

//        $distance ? asort($distance) : $distance =  array();
        return array('driver_info' => $driver_info, 'count' => $count);
    }


    //订单详情页面
    public function detail()
    {
        $common_id = input('get.common_id');
        $config['driver_url'] = url('fleet_driver_table', 'common_id=' . $common_id);
        $order_logic = new OrderLogic();
        $info = $order_logic->getOrderCommonById($common_id, 'a.*,a.order_status as status,start_name,arrive_name,car_plate,driver_name,driver_phone,car_brand,car_model,color');

        $info['car_plate'] = Security::decrypt($info['car_plate']) ?: '';
        $info['journey'] = intval($info['journey']);
        $info['dis'] = intval($info['dis']);
        $info['car_brand'] = Security::decrypt($info['car_brand']) ?: '';
        $info['car_model'] = Security::decrypt($info['car_model']) ?: '';
        $info['color'] = Security::decrypt($info['color']) ?: '';
        $info['cancel_price'] = $info['cancel_price']?number_format(($info['cancel_price']/100), 2):'-';

        //用户手机号
        $user_logic = new UserLogic();
        $info['user_phone'] = Security::decrypt($user_logic->getUserByUid($info['member_id'], 'user_phone')['user_phone']);
        $info['driver_phone_number'] = Security::decrypt($info['driver_phone']) ?: '';
        unset($info['driver_phone']);

        //退款订单金额
        if ($info['status'] == 25) {
            $info['refund_money'] = $info['need_price'];
        }
        if ($info['is_pay'] == 1) {
            //查询抵扣金额
            $gifts_money            = Db::name('user_recharge')->where(['uid' => $info['member_id'], 'out_trade_no' => $info['order_sn'], 'money_statement' => 6])->value('gifts_money');
//            $info['gifts_money']    = sprintf("%.2f", $gifts_money /100);
        }else{
            $info['gifts_money']    = '-';
        }
        //司机罚款金额
        $fine_money_res = Db::table('xm_driver_wallet_record')->field('money')->where(['common_id' => $info['id'], 'record_type' => 3])->find();
        $info['driver_fine_money'] = $fine_money_res['money'];

        if ($info) {
//			$allot_driver = $this->findAllotDriver($order_logic,$info);
            switch ($info['status']) {
                case 0:
                    $config['color'] = 'grey';
                    break;
                case 10:
                case 15:
                    $config['color'] = 'red';
                    break;
                case 20:
                    $config['color'] = 'green';
                    break;
                case 25:
                    $config['color'] = 'darkorange';
                    break;
                case 30:
                    $config['color'] = 'seagreen';
                    break;
                case 35:
                    $config['color'] = 'skyblue';
                    break;
                case 40:
                    $config['color'] = 'deepskyblue';
                    break;
                case 45:
                    $config['color'] = 'slateblue';
                    break;
                default:
                    $config['color'] = 'fuchsia';
                    break;
            }

            $info = decode_array_inter($info);

//			$info['passenger_number'] = $order_logic->orderCountByCommonId($info['id']);
            $passenger_number_res = Db::table('inter_order_common')->field('passenger_number,fleet_price,refund_fee')->where(['id' => $info['id']])->find();
            $info['passenger_number'] = $passenger_number_res['passenger_number'];
            //车队收入
            $info['fleet_price'] = $passenger_number_res['fleet_price']?number_format(($passenger_number_res['fleet_price']/100), 2):'0.00';
            //退款金额
            $info['refund_money'] = $passenger_number_res['refund_fee']?number_format(($passenger_number_res['refund_fee']/100), 2):'0.00';

            //司机收入
            $income_data = Db::table('xm_driver_wallet_record')->field('money')->where(['driver_id'=>$info['driver_id'],'common_id'=>$info['id'],'order_sn'=>$info['order_sn']])->find();
            $info['driver_income'] = $income_data['money']?number_format(($income_data['money']/100), 2):'0.00';

            //乘客评价司机 内容
            $comment_data = Db::table('xm_comment c')
                ->join(['xm_comment_dict'=> 'd'],'c.comment_dict_id = d.id','LEFT')
                ->join(['xm_comment_label_dict'=> 'l'],'c.label_id = l.id','LEFT')
                ->field('content,time,service_rank,title,label')
                ->where(['common_id' => $info['id'],'order_type'=>3])
                ->find();
            $info['score'] = $comment_data['service_rank'];  //评分
            $info['detail'] = $comment_data['content'].' '.$comment_data['title'].' '.$comment_data['label']; //评价
            $info['evaluate_time'] = empty($comment_data['time'])?'--':date('Y-m-d H:i:s',$comment_data['time']); //评价时间

            $order_area = Db::table('xm_region a')
                ->field('a.region_name as area_name, c.region_name as city_name, p.region_name as province_name')
                ->join(['xm_region' => 'c'], 'a.parent_id=c.region_id', 'LEFT')
                ->join(['xm_region' => 'p'], 'c.parent_id=p.region_id', 'LEFT')
                ->where('a.region_code = ' . $info['start_code'])
                ->find();
            $info['area'] = $order_area['province_name'].'/'.$order_area['city_name'].'/'.$order_area['area_name'];

            //车辆信息
            $info['car_info'] = $info['color'].'-'.$info['car_model'];

            //司机接单（派单时间）
            $info['order_taker_time'] = empty($info['order_taker_time'])?'--':$info['order_taker_time'];

            //订单明细
            $order_detail = array(
                'order_sn' => '订单编号',
                'member_id' => '用户UID',
                'area' => '省/市/区',
                'order_status' => '订单状态',
                'user_phone' => '下单人手机号',
                'order_time' => '下单时间',
                'start_name' => '出发地点',
                'arrive_name' => '目的地点',
                'passenger_number' => '乘客人数',
                'start_time' => '预约出发时间',
                'contact_number' => '联系人手机号',
                'is_contract' => '是否包车',
                'remarks' => '备注信息',
                'order_taker_time' => '派单时间',
            );

            //已支付订单信息 / 未支付订单
            $order_info_pay = array(
                'driver_phone_number' => '司机手机号',
                'driver_name' => '司机姓名',
                'car_info' => '车辆信息',
                'car_plate' => '车牌号',
                'fleet_name' => '归属车队',
                'drive_pickup_time' => '出发时间',
                'passenger_comfirm_arrival_time' => '达到起点时间',
                'dep_time' => '上车时间',
                'dest_time' => '下车时间',
//                'cancel_reason' => '取消原因',
                'dis' => '起止地行程公里数',
//                'journey' => '全部行程公里',
            );

            //用户取消订单消息
            $order_info_cancel = array(
                'cancel_time' => '取消时间',
                'cancel_reason' => '取消原因',
            );

            //费用明细
            $fee_detail = array(
                'is_pay' => '付款状态',
                'order_price' => '订单金额',
                'unit_price' => '订单单价',
                'coupon_price' => '优惠金额',
                'gifts_money' => '抵扣金额',
                'need_price' => '实付金额',
                'paytool' => '支付方式',
                'pay_time' => '支付时间',
                'driver_income' => '司机收入',
                'platform_price' => '平台费(包含车队收入)',
                'fleet_price' => '车队收入',
                'cancel_price' => '取消扣费',
//                'driver_fine_money' => '司机罚款',
                'refund_money' => '实际退款',

            );

            //取消订单费用明细 [未支付]
            $cancel_detail = array(
                'is_pay' => '付款状态',
                'order_price' => '订单金额',
                'cancel_price' => '取消扣费',
            );

            //评价信息
            $comment_detail = array(
                'score' => '评分',
                'evaluate_time'=>'评价时间',
                'detail' => '评价内容'
            );

            //列表模板字段
//			$config['fields'] = $this->column;

//            if ($info['is_pay'] == 1) {  //已支付
                if($info['status'] == 50) { //已评价 已完成 订单
//                    $config['fields'] = array_merge($order_detail, $fee_detail, $comment_detail);
                    $config['fields'] = array_merge($order_detail, $order_info_pay);
                    $config['fee_info'] = $fee_detail;
                    $config['comment_info'] = $comment_detail;
                } elseif(in_array($info['status'],[10,11,12,15,16])) { //取消订单 10系统取消，11因故取消，12有责取消，15用户取消，16客服取消，
                    $config['fields'] = array_merge($order_detail, $order_info_cancel);
                    if($info['is_pay'] == 1) { //已支付
                        $config['fee_info'] = $fee_detail;
                    } else { //未支付
                        $config['fee_info'] = $cancel_detail;
                    }
                } else {
                    $config['fields'] = $order_detail;
                    $config['fee_info'] = $fee_detail;
                }
//            }
//            else { //未支付
//                $config['fields'] = array_merge($order_detail, $order_info_cancel);;
//            }
            switch ($info['is_pay']) {
                case 0 :
                    $info['is_pay'] = "<span style='color: red;'>未支付</span>";
                    break;
                case 1 :
                    $info['is_pay'] = "<span style='color: green;'>已付款</span>";
            }

            //车队名称
            $fleet_info = Db::connect('db2')->table('fleet')->field('name')->where(['id' => $info['fleet_id']])->find();
            $info['fleet_name'] = $fleet_info['name'] ?: '';

            if ($info['is_contract'] == 1) {
                $charter_info = Db::table('inter_charter_car')->field('model_name')->where('id', $info['charter_car_id'])->find();
                $info['is_contract'] = "<span style='color: green;'>" . $charter_info['model_name'] . "</span>";
            } else {
                $info['is_contract'] = '否';
            }

            $config['info'] = $info;
            $config['url'] = url('allot');
//            $config['driver_infos'] = $allot_driver['driver_info'];

///			$config['driver_infos'] = decode_array_inter_2($allot_driver['driver_info'], $type='car_info');
//			$config['distance'] = $allot_driver['distance'];
            $this->assign($config);
            if (input('get.from') == 'refund') {
                return json(array('status' => 1, 'html' => $this->fetch('detail_table')));
            }
            return view();
        } else {
            if (input('get.from') == 'refund') {
                return json(array('status' => 0, 'msg' => '没有支付记录'));
            }
        }
    }

    /**
     * 订单删除
     * @param string
     * @param int is_del 1是2否
     * @return string 成功时返回
     */
    public function interOrderDel()
    {
        $id = input('post.id');
        $res = Db::table('inter_order_common')->where('id', $id)->update(['is_del' => 1]);//软删除1是2否
        if ($res) {
            echo json_encode(['code' => 1, 'msg' => '删除成功']);
            exit;
        } else {
            echo json_encode(['code' => 0, 'msg' => '删除失败']);
            exit;
        }
    }

    //取消
    public function cancel()
    {
        $data['id'] = input('post.id');
        $data['cancel_reason'] = input('post.cancel_reason');
        $data['order_status'] = 16;//客服取消
        $order_logic = new OrderLogic();
        $info = $order_logic->getOrderCommonById($data['id'], 'order_status,subs_id,secret_no,a.driver_id');
        if (empty($data['id']) || empty($data['cancel_reason'])) {
            return json(array('status' => 0, 'msg' => '参数异常，联系技术人员'));
        }
        if (empty($info)) {
            return json(array('status' => 0, 'msg' => '不存在的订单'));
        }
        switch ($info['order_status']) {
            case 0:
                break;
            case 10:
            case 11:
            case 12:
            case 15:
            case 16:
                return json(array('status' => 0, 'msg' => '请勿重复操作'));
                break;
            case 20:
            case 25:
                return json(array('status' => 0, 'msg' => '已在处理退款，请勿操作'));
                break;
            case 41:
            case 45:
            case 47:
            case 50:
                return json(array('status' => 0, 'msg' => '不可取消'));break;
            default:;
        }
        if ($info['subs_id'] && $info['secret_no']) {
            Tools::AXBUnbind($info['subs_id'], $info['secret_no']);
        }
        $data['cancel_time'] = time();
        $data['order_taker_time'] = 0;
        $order_logic->renewOrderCommon(array(), $data);
        $this->changeOrderDriverCache($info['driver_id'], $data['id'], 2);//删除订单司机关系缓存
        $this->renewInterOrderMsg($data['id']);//更新城际订单后台通知信息
        $order_local_cache = Cache::pull('order_local_' . $data['id']);
        if ($order_local_cache) {
            $trip_logic = new TripLogic();
            $trip_logic->createLocal($order_local_cache, $data['id']);
        }
        return json(array('status' => 1, 'msg' => '操作成功'));
    }

    //搜索
    public function search()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $map = $this->dealInput(input('get.'));
        $is_real = empty(input('get.all_order'))?'':input('get.all_order');  //订单性质 1 普通订单 2 测试订单

        if ($this->map['start_code']) {
            $map['start_code'] = $this->map['start_code'];
        }

        //******搜索起点
        $start_arean = input('get.start_arean');
        if ($start_arean) {
            $start_region_arr = Db::table('inter_arean a')->field('a.id,r.region_level,r.region_code,r.region_name,r.parent_id')->join(['xm_region' => 'r'], 'a.area_id=r.region_id')->where('a.id', $start_arean)->find();
            if (($start_region_arr['region_level'] == 3) && ($start_region_arr['region_name'] != '市辖区')) {
                $this->map['start_code'] = $map['start_code'] = $start_region_arr['region_code'];
            }
            if ($start_region_arr['region_name'] == '市辖区') {
                $start_region_arr = Db::table('xm_region')->field('region_code')->where('parent_id', $start_region_arr['parent_id'])->select();
                $code_arr = array();
                foreach ($start_region_arr as $key => $value) {
                    $code_arr[] = $value['region_code'];
                }
                $this->map['start_code'] = $map['start_code'] = ['in', implode(',', $code_arr)];
            }
        }
        $end_arean = input('get.end_arean');

        if ($end_arean) {
            $end_region_arr = Db::table('inter_arean a')->field('a.id,r.region_level,r.region_code,r.region_name,r.parent_id')->join(['xm_region' => 'r'], 'a.area_id=r.region_id')->where('a.id', $end_arean)->find();
            if (($end_region_arr['region_level'] == 3) && ($end_region_arr['region_name'] != '市辖区')) {
                $this->map['arrive_code'] = $map['arrive_code'] = $end_region_arr['region_code'];
            }
            if ($end_region_arr['region_name'] == '市辖区') {
                $end_region_arr = Db::table('xm_region')->field('region_code')->where('parent_id', $end_region_arr['parent_id'])->select();
                $code_arr1 = array();
                foreach ($end_region_arr as $key => $value) {
                    $code_arr1[] = $value['region_code'];
                }
                $this->map['arrive_code'] = $map['arrive_code'] = ['in', implode(',', $code_arr1)];
            }
        }
        //****搜索起点end
        $order_logic = new OrderLogic();
        $field = "a.*,a.order_status as status,start_address_name,end_address_name,car_plate,driver_name,driver_phone";
        $map['a.is_del'] = 2;

        $res = $order_logic->getOrderCommon($map, $field, true, 'a.id desc', $page, $limit,$is_real);

        $count = Db::table('inter_order_common a')
            ->join(['inter_car_banci' => 'd'], 'a.banci_id=d.id', 'LEFT')
            ->join(['xm_driver_base' => 'e'], 'a.driver_id=e.driver_id', 'LEFT')
            ->join(['xm_car_info' => 'f'], 'a.car_id=f.car_id', 'LEFT')
            ->join(['inter_order_comment' => 'g'], 'g.common_id=a.id', 'LEFT')
            ->where($map)
            ->where(function ($query) use ($is_real) {
                $whiteList = Db::name('white_list')->order('id desc')->find();
                if (!empty($is_real) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))) {
                    if ($is_real == 1) {            //普通订单
                        $query->where(['a.member_id' => ['not in', $whiteList['uid_str']]]);
                        $query->whereOr(['a.driver_id' => ['not in', $whiteList['driver_str']]]);
                    } elseif ($is_real == 2) {      //测试订单
                        $query->where(['a.member_id' => ['in', $whiteList['uid_str']]]);
                        $query->where(['a.driver_id' => ['in', $whiteList['driver_str']]]);
                    }
                }
            })
            ->count();

//        $count = Db::table('inter_order_common')->where($this->map)->count();
//		$res = decode_array_inter_2($res,$type='car_info');

        $whiteList = Db::name('white_list')->order('id desc')->find();

        foreach ($res as $key => $value) {
            //测试账号名单
            if (!empty($whiteList['uid_str']) && in_array($value['member_id'], explode(',', $whiteList['uid_str']))) {
                $res[$key]['user_type'] = 1;
            } else {
                $res[$key]['user_type'] = 0;
            }
            //查询司机真实手机号码
            if (!empty($value['real_phone'])) {
                $res[$key]['real_phone'] = Security::decrypt($value['real_phone']);
            } else {
                $res[$key]['real_phone'] = '-';
            }
            //类型
            if (!empty($whiteList['driver_str']) && in_array($value['driver_id'], explode(',', $whiteList['driver_str']))) {
                $res[$key]['driver_type'] = 1;
            } else {
                $res[$key]['driver_type'] = 0;
            }

            foreach ($value as $k => $v) {
                if ($k == 'order_status') {
                    $res[$key][$k] = inter_order_status()[$v];
                }
            }
        }

////		$res = decode_array_inter_2($res, $type='car_info');
//
//        foreach ($res as $key => $value) {
//            foreach ($value as $k => $v) {
//                if ($k == 'order_status') {
//                    $res[$key][$k] = inter_order_status()[$v];
//                }
//            }
//        }

        $car_logic = new CarLogic();
        $driver_logic = new DriverLogic();
        $user_logic = new UserLogic();
        foreach ($res as $key => $val) {

            $order_area = Db::table('xm_region a')
                ->field('a.region_name as area_name, c.region_name as city_name, p.region_name as province_name')
                ->join(['xm_region' => 'c'], 'a.parent_id=c.region_id', 'LEFT')
                ->join(['xm_region' => 'p'], 'c.parent_id=p.region_id', 'LEFT')
                ->where('a.region_code = ' . $val['start_code'])
                ->find();
            $passenger_res = Db::table('inter_order_common')->field('passenger_number')->where(['id' => $val['id']])->find();
            $res[$key]['passenger'] = $passenger_res['passenger_number'];
            //$res[$key]['ban'] = $val['start_address_name'].'-'.$val['end_address_name'];
            $res[$key]['user_phone'] = Security::decrypt($user_logic->getUserByUid($val['member_id'], 'user_phone')['user_phone']);
            $res[$key]['driver_phone'] = Security::decrypt($val['driver_phone']) ?: '';
            $res[$key]['car_plate'] = Security::decrypt($val['car_plate']) ?: '';
            $res[$key]['area'] = $order_area['province_name'].'/'.$order_area['city_name'].'/'.$order_area['area_name'];
            $res[$key]['order_time'] = date('Y-m-d H:i:s', $val['order_time']);
            $res[$key]['start_time'] = date('Y-m-d H:i:s', $val['start_time']);

            //车队名称
            $fleet_info = Db::connect('db2')->table('fleet')->field('name')->where(['id' => $val['fleet_id']])->find();
            $res[$key]['fleet_name'] = $fleet_info['name'] ?: '';

            //是否包车
            if ($val['is_contract']) {
                $charter_car_info = Db::table('inter_charter_car')->field('model_name')->where(['id' => $val['charter_car_id']])->find();
                $res[$key]['is_contract'] = $charter_car_info['model_name'] ?: '';
            } else {
                $res[$key]['is_contract'] = '否';
            }
        }

        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'limit' => $limit,
            'count' => $count,
            'data' => $res
        ));
    }

    //分配
    public function allot()
    {
        $data_post = (input('post.'));

        $config['status'] = 0;
        $data_post['common_id'] = intval($data_post['common_id']);
        $data['driver_id'] = $data_post['driver_id'] == 'cancel' ? 0 : intval($data_post['driver_id']);

        if (empty($data_post['common_id']) || empty($data_post['driver_id'])) {
            $config['msg'] = '参数异常';
            return json($config);
        }
        $order_logic = new OrderLogic();
        $driver_logic = new DriverLogic();
        //       $info = $order_logic->getOrderCommonById($data_post['common_id'],'*');
        $info = $order_logic->getOrderCommonById($data_post['common_id']);

        if ($data['driver_id'] > 0 && !in_array($info['order_status'],[0,30])) {
            $config['msg'] = '该订单无法分配';
            return json($config);
        }
        if ($data_post['driver_id'] == 'cancel' && $info['order_status'] != 35) {
            $config['msg'] = '该订单无法取消分配';
            return json($config);
        }

        if ($data_post['driver_id'] == 'cancel') {//取消派单
            $driver_info = $driver_logic->getInfoByDid($info['driver_id'], 'a.car_id,is_goon,registration_id,seats,driver_phone,commonly_used_number');
        } else { //派单
            $driver_info = $driver_logic->getInfoByDid($data_post['driver_id'], 'a.car_id,is_goon,registration_id,seats,driver_phone,a.car_plate,b.driver_name,commonly_used_number');
        }

        //检测司机的常用号码  若不存在 则取 注册手机号
        $driver_phone = $driver_info['commonly_used_number'] ?: $driver_info['driver_phone'];

        $user_info = $order_logic->getOrderCommonDetailById($data_post['common_id'], 'b.uid,b.registration_id,b.user_phone,a.contact_number');

        $data['id'] = $data_post['common_id'];
        $data['car_id'] = 0;
        $data['order_status'] = $info['order_status'] == 30 ? 35 : 30;
        $data['subs_id'] = 0;
        $data['secret_no'] = '';
        //如果存在私密号码，则取消绑定
        if ($info['subs_id'] && $info['secret_no']) {
            Tools::AXBUnbind($info['subs_id'], $info['secret_no']);
        }
        //存在司机id，将订单的状态改为已派单

        if ($data['driver_id']) {
            /*************判断司机分配的乘客是否已满***********************/

//			$map_order_common['order_status'] = 35;//已分配
//			$map_order_common['a.driver_id'] = $data['driver_id'];
//			$common_id_arr = $order_logic->getOrderCommon($map_order_common,'a.id');
//
//            $passenger_count_res = Db::table('inter_order_common')->field('passenger_number')->where(['id'=>$data['id']])->find();
//            $passenger_count = $passenger_count_res['passenger_number']; //本订单的乘客数
//
//			$passenger_count_allot = 0;//已分配该司机的乘客数
//			foreach ($common_id_arr as $value){
////				$passenger_count_allot += $order_logic->orderCountByCommonId($value['id']);
//                $passenger_count_allot_res = Db::table('inter_order_common')->field('passenger_number')->where(['id'=>$value['id']])->find();
//                $passenger_count_allot += $passenger_count_allot_res['passenger_number'];
//			}
//
//			if($passenger_count>($driver_info['seats']-$passenger_count_allot)){
//				$config['msg'] = '本订单乘客数超过该司机能载乘客数,请重新分配司机';
//				return json($config);
//			}

            /*************判断司机分配的乘客是否已满***********************/
            $data['car_id'] = $driver_info['car_id'];
            $data['order_status'] = 35;

            /**
             * $bind = Tools::AXBBind(des_decrypt($driver_info['driver_phone']),$info['contact_number'],date('Y-m-d H:i:s',$info['start_time']),$data_post['common_id']);    //des_decrypt() 加密方法已废弃
             **/
//            //检测司机的常用号码  若不存在 则取 注册手机号
//            $driver_phone = $driver_info['commonly_used_number']?:$driver_info['driver_phone'];

            $bind = Tools::AXBBind(Security::decrypt($driver_phone), $info['contact_number'], date('Y-m-d H:i:s', $info['start_time']), $data_post['common_id']);

            //隐私小号 绑定
            if ($bind['status'] == 200) { //成功
                $data['subs_id'] = $bind['data']['subsId'];
                $data['secret_no'] = $bind['data']['secretNo'];
            }

            $data['order_taker_time'] = time(); //司机接单(手动派单)时间
        }

        $res = $order_logic->renewOrderCommon(array('id' => $data['id']), $data);

        if ($res === false) {
            $config['msg'] = '派单出错，请联系技术人员';
            return $config;
        }
        $config['status'] = 1;
        $config['msg'] = '操作成功';
        $data_msg['mes_type'] = 5;//派单通知
        $inter_driver_logic = new InterDriverLogic();
        switch ( ['driver_id']) {
            //取消分派订单
            case 0:
                $this->dealDriverStatus($info['driver_id']);//判断并修改司机状态

                Db::table('inter_order_common')->where('id', $data_post['common_id'])->update(['is_cancel' => 1,'order_taker_time'=>0]); // 改变订单是否被取消的状态  0 未取消  1 已取消

                $data_msg['title'] = "取消分配订单";
                $data_msg_user['title'] = '订单已取消分配';
                $data_msg['content'] = $data_msg_user['content'] = "您的订单编号{$info['order_sn']},出发时间:" .
                    date('Y-m-d H:i', $info['start_time']) . ",出发地点:{$info['start_name']}的订单被取消分配";
                $type = 2;

                //socket 取消订单消息推送
                $socket_data['orderId'] = $data_post['common_id'];
                $socket_data['type'] = 2;  //类型 1. 派单 2.取消派单
                //java接口 socket推送
                $url = Env::get('javaPush'.ENV.'_host') . "/websocket/inter/assignOrder";

                //参数加密
                $post_url_param = urldecode(http_build_query($socket_data));
                $post_param['encode'] = Security::encrypt($post_url_param);
                //curl请求
                $res = https_request($url, $post_param);
                $return_data = json_decode($res,true);

                break;
            //派单给司机，将司机改为等客中
            default:
                if ($driver_info['is_goon'] == 2) {
                    $driver_logic->renewDriver(array('driver_id' => $data['driver_id']), array('is_goon' => 3));
                }
                $data_msg['title'] = "您有新订单";
                $data_msg_user['title'] = '订单已分配';
                $data_msg['content'] = "订单编号{$info['order_sn']},出发时间:" .
                    date('Y-m-d H:i', $info['start_time']) . ",出发地点:{$info['start_name']},到达地点:{$info['arrive_name']}";
                $data_msg_user['content'] = "您的订单编号{$info['order_sn']},出发时间:" .
                    date('Y-m-d H:i', $info['start_time']) . ",出发地点:{$info['start_name']}的订单已分配,请在行程中查看";
                $type = 1;


                //socket 订单消息推送
                $socket_data['orderId'] = $data_post['common_id'];
                $socket_data['type'] = 1;  //类型 1. 派单 2.取消派单
                //java接口 socket推送
                $url = Env::get('javaPush'.ENV.'_host') . "/websocket/inter/assignOrder";

                //参数加密
                $post_url_param = urldecode(http_build_query($socket_data));
                $post_param['encode'] = Security::encrypt($post_url_param);
                //curl请求
                $res = https_request($url, $post_param);
                $return_data = json_decode($res,true);

                break;
        }

        $this->dealPayLog($data_post['common_id'], $data['driver_id'], $type);//变更支付日志信息
        $did = $info['driver_id'] ?: $data['driver_id'];
        $this->createAllotLog($data_post['common_id'], $did, $type);//添加派单操作日志信息
        $data_msg_user['send_time'] = time();
        $data_msg_user['type'] = 2;
        $data_msg_user['order_type'] = 3;
        $data_msg_user['uid'] = $user_info['uid'];
        Db::table('xm_passenger_message')->insert($data_msg_user);//站内信息通知用户
        $inter_driver_logic->createDriverMsg($data_msg, $did);//站内信息通知司机
        $this->renewInterOrderMsg($data_post['common_id']);//更新城际订单后台通知信息
        $this->changeOrderDriverCache($did, $data_post['common_id'], $type);//增加或删除订单司机关系的缓存

        if ($data['driver_id'] == '0') {   //取消分派订单

            $driver_info['registration_id'] && Tools::JPush($data_msg['title'], $data_msg['content'], $driver_info['registration_id'], 'innerDriver', 'cancelIntercityOrder');//司机推送

//            $user_info['registration_id']&&Tools::JPush($data_msg_user['title'],$data_msg_user['content'],$user_info['registration_id'],'user','');//用户推送

            //**城际订单指派单被取消给司机发短信
//            $phone = Security::decrypt($driver_info['driver_phone']);
            $content['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
            $content['start_name'] = $info['start_name'];
            Tools::sendMes($driver_phone, $content, 34);

//            //**城际订单指派单被后台管理员取消给乘客发短信
//            $phone = Security::decrypt($user_info['user_phone']);
//            $content['start_time'] = date('Y-m-d H:i:s',$info['start_time']);
//            $content['start_name'] = $info['start_name'];
//            Tools::sendMes($phone,$content,35);
        } else {
            //redis
            //查询 是否为 改派的订单
            $cancel_res = Db::table('inter_order_common')->field('is_cancel')->where('id', $data_post['common_id'])->find();

            if ($cancel_res['is_cancel']) { // 改派

                //改派时 极光推送 信息文字
//                //司机
//                $data_msg['title'] = "您有新订单";
//                $data_msg['content'] = "订单编号{$info['order_sn']},出发时间:".
//                    date('Y-m-d H:i',$info['start_time']).",出发地点:{$info['start_name']},到达地点:{$info['arrive_name']}";
                //乘客
                $driver_info['driver_name'] = mb_substr($driver_info['driver_name'], 0, 1, 'utf-8') . '师傅';
                $driver_info['car_plate'] = Security::decrypt($driver_info['car_plate']);
                $data_msg_user['title'] = '订单已改派';
                $data_msg_user['content'] = "您的订单编号{$info['order_sn']},出发时间:" .
                    date('Y-m-d H:i', $info['start_time']) . ",出发地点:{$info['start_name']}的订单已改派给司机:{$driver_info['driver_name']},车牌号:{$driver_info['car_plate']},请在行程中查看";

                $driver_info['registration_id'] && Tools::JPush($data_msg['title'], $data_msg['content'], $driver_info['registration_id'], 'innerDriver', 'sendIntercityOrder');//司机推送

                $user_info['registration_id'] && Tools::JPush($data_msg_user['title'], $data_msg_user['content'], $user_info['registration_id'], 'user', '');//用户推送

                //**给司机发送短信
//                $phone = Security::decrypt($driver_info['driver_phone']);
                $content['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
                $content['start_name'] = $info['start_name'];
                $content['arrive_name'] = $info['arrive_name'];
                Tools::sendMes($driver_phone, $content, 32);

                //**给用户发送短信 或者 给下单人发短信
                //判断是否是给他人叫车[用户手机号 和 联系人号码是否一致]
                $user_phone = Security::decrypt($user_info['user_phone']);
                $content['driver_name'] = $driver_info['driver_name'];
                $content['car_plate'] = $driver_info['car_plate'];

                $content['driver_name'] = mb_substr($driver_info['driver_name'], 0, 1, 'utf-8') . '师傅';
//                $content['driver_number'] = empty($data['secret_no'])?Security::decrypt($driver_info['driver_phone']):$data['secret_no'];
                $content['driver_number'] = empty($data['secret_no']) ? $driver_phone : $data['secret_no'];
                $content['start_time'] = date('Y-m-d H:i', $info['start_time']);
                $content['line'] = $info['start_name'] . '-' . $info['arrive_name'];

                if ($user_info['contact_number'] == $user_phone) {
                    Tools::sendMes($user_phone, $content, 38);
                } else {
                    Tools::sendMes($user_info['contact_number'], $content, 41);
                }

            } else {  //手动指派订单
                $driver_info['registration_id'] && Tools::JPush($data_msg['title'], $data_msg['content'], $driver_info['registration_id'], 'innerDriver', 'sendIntercityOrder');//司机推送
                $user_info['registration_id'] && Tools::JPush($data_msg_user['title'], $data_msg_user['content'], $user_info['registration_id'], 'user', '');//用户推送

                //**给司机发送短信
//                $phone = Security::decrypt($driver_info['driver_phone']);
                $content['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
                $content['start_name'] = $info['start_name'];
                $content['arrive_name'] = $info['arrive_name'];
                Tools::sendMes($driver_phone, $content, 32);

                //**给用户发送短信 或者 给下单人发短信
                //判断是否是给他人叫车[用户手机号 和 联系人号码是否一致]
                $user_phone = Security::decrypt($user_info['user_phone']);
                $content['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
                $content['start_name'] = $info['start_name'];

                $content['number'] = $user_phone;
                $content['driver_name'] = mb_substr($driver_info['driver_name'], 0, 1, 'utf-8') . '师傅';
                $content['car_plate'] = Security::decrypt($driver_info['car_plate']);
                $content['driver_number'] = empty($data['secret_no']) ? $driver_phone : $data['secret_no'];
                $content['start_time'] = date('Y-m-d H:i', $info['start_time']);
                $content['line'] = $info['start_name'] . '-' . $info['arrive_name'];

                if ($user_info['contact_number'] == $user_phone) {
                    Tools::sendMes($user_phone, $content, 33);
                } else {
                    Tools::sendMes($user_info['contact_number'], $content, 40);
                }

            }
        }

        return json($config);
    }

    //导出数据
    public function excel()
    {
        $all = input('get.all');
        $page = input('get.page') ?: 1;
        $limit = $all == 1 ? 1000 : input('get.limit');
        $map = $this->dealInput(input('get.'));

        $is_real = empty(input('get.all_order'))?'':input('get.all_order');  //订单性质 1 普通订单 2 测试订单

        if ($this->map['start_code']) {
            $map['start_code'] = $this->map['start_code'];
        }

        //******搜索起点
        $start_arean = input('get.start_arean');
        if ($start_arean) {
            $start_region_arr = Db::table('inter_arean a')->field('a.id,r.region_level,r.region_code,r.region_name,r.parent_id')->join(['xm_region' => 'r'], 'a.area_id=r.region_id')->where('a.id', $start_arean)->find();
            if (($start_region_arr['region_level'] == 3) && ($start_region_arr['region_name'] != '市辖区')) {
                $this->map['start_code'] = $map['start_code'] = $start_region_arr['region_code'];
            }
            if ($start_region_arr['region_name'] == '市辖区') {
                $start_region_arr = Db::table('xm_region')->field('region_code')->where('parent_id', $start_region_arr['parent_id'])->select();
                $code_arr = array();
                foreach ($start_region_arr as $key => $value) {
                    $code_arr[] = $value['region_code'];
                }
                $this->map['start_code'] = $map['start_code'] = ['in', implode(',', $code_arr)];
            }
        }
        $end_arean = input('get.end_arean');

        if ($end_arean) {
            $end_region_arr = Db::table('inter_arean a')->field('a.id,r.region_level,r.region_code,r.region_name,r.parent_id')->join(['xm_region' => 'r'], 'a.area_id=r.region_id')->where('a.id', $end_arean)->find();
            if (($end_region_arr['region_level'] == 3) && ($end_region_arr['region_name'] != '市辖区')) {
                $this->map['arrive_code'] = $map['arrive_code'] = $end_region_arr['region_code'];
            }
            if ($end_region_arr['region_name'] == '市辖区') {
                $end_region_arr = Db::table('xm_region')->field('region_code')->where('parent_id', $end_region_arr['parent_id'])->select();
                $code_arr1 = array();
                foreach ($end_region_arr as $key => $value) {
                    $code_arr1[] = $value['region_code'];
                }
                $this->map['arrive_code'] = $map['arrive_code'] = ['in', implode(',', $code_arr1)];
            }
        }
        //****搜索起点end
        $order_logic = new OrderLogic();
        $map['is_del'] = 2;
        $field = "a.*,a.order_status as status,start_address_name,end_address_name,car_plate,driver_name,driver_phone";
        $res = $order_logic->getOrderCommon($map, $field, true, 'a.id desc', $page, $limit,$is_real);

        $whiteList = Db::name('white_list')->order('id desc')->find();

        foreach ($res as $key => $value) {
            //测试账号名单
            if (!empty($whiteList['uid_str']) && in_array($value['member_id'], explode(',', $whiteList['uid_str']))) {
                $res[$key]['user_type'] = 1;
            } else {
                $res[$key]['user_type'] = 0;
            }
            //查询司机真实手机号码
            if (!empty($value['real_phone'])) {
                $res[$key]['real_phone'] = Security::decrypt($value['real_phone']);
            } else {
                $res[$key]['real_phone'] = '-';
            }
            //类型
            if (!empty($whiteList['driver_str']) && in_array($value['driver_id'], explode(',', $whiteList['driver_str']))) {
                $res[$key]['driver_type'] = 1;
            } else {
                $res[$key]['driver_type'] = 0;
            }

            foreach ($value as $k => $v) {
                if ($k == 'order_status') {
                    $res[$key][$k] = inter_order_status()[$v];
                }
            }
        }

//		$res = decode_array_inter_2($res);

//        foreach ($res as $key => $value) {
//            foreach ($value as $k => $v) {
//                if ($k == 'order_status') {
//                    $res[$key][$k] = inter_order_status()[$v];
//                }
//            }
//        }

        $car_logic = new CarLogic();
        $driver_logic = new DriverLogic();
        $user_logic = new UserLogic();

        foreach ($res as $key => $val) {
            $order_area = Db::table('xm_region a')
                ->field('a.region_name as area_name, c.region_name as city_name, p.region_name as province_name')
                ->join(['xm_region' => 'c'], 'a.parent_id=c.region_id', 'LEFT')
                ->join(['xm_region' => 'p'], 'c.parent_id=p.region_id', 'LEFT')
                ->where('a.region_code = ' . $val['start_code'])
                ->find();
            //退款金额
            $res[$key]['refund_money'] = $val['refund_fee']?number_format(($val['refund_fee']/100), 2):'-';

            //有责取消扣款
            $res[$key]['cancel_price'] = $val['cancel_price']?number_format(($val['cancel_price']/100), 2):'-';

            //司机罚款金额
            $fine_money_res = Db::table('xm_driver_wallet_record')->field('money')->where(['common_id' => $val['id'], 'record_type' => 3])->find();
            $res[$key]['driver_fine_money'] = sprintf("%.2f", ($fine_money_res['money'] / 100));

            $res[$key]['driver_name'] = $val['driver_name'];
            $res[$key]['user_phone'] = Security::decrypt($user_logic->getUserByUid($val['member_id'], 'user_phone')['user_phone']);


            $res[$key]['driver_phone'] = Security::decrypt($val['driver_phone']) ?: '';
            $res[$key]['car_plate'] = Security::decrypt($val['car_plate']) ?: '';

            $res[$key]['area'] = $order_area['province_name'].'/'.$order_area['city_name'].'/'.$order_area['area_name'];
            $res[$key]['order_time'] = empty($val['order_time'])?'':date('Y-m-d H:i:s', $val['order_time']);
            $res[$key]['start_time'] = empty($val['start_time'])?'':date('Y-m-d H:i:s', $val['start_time']);
            $res[$key]['pay_time'] = empty($val['pay_time'])?'':date('Y-m-d H:i:s', $val['pay_time']);
            $res[$key]['paytool'] = pay_type()[$val['paytool']];

            $is_pay_info = [
                '0' => '未支付',
                '1' => '已支付'
            ];
            $res[$key]['is_pay'] = $is_pay_info[$val['is_pay']];
            //车队名称
            $fleet_info = Db::connect('db2')->table('fleet')->field('name')->where(['id' => $val['fleet_id']])->find();
            $res[$key]['fleet_name'] = $fleet_info['name'] ?: '';

            //是否包车
            if ($val['is_contract']) {
                $charter_car_info = Db::table('inter_charter_car')->field('model_name')->where(['id' => $val['charter_car_id']])->find();
                $res[$key]['is_contract'] = $charter_car_info['model_name'] ?: '';
            } else {
                $res[$key]['is_contract'] = '否';
            }

            //司机收入
            $income_data = Db::table('xm_driver_wallet_record')->field('money')->where(['driver_id'=>$val['driver_id'],'common_id'=>$val['id'],'order_sn'=>$val['order_sn']])->find();
            $res[$key]['driver_income'] = $income_data['money']?number_format(($income_data['money']/100), 2):'-';
        }

//		$header = array_merge(array('id'=>'ID','car_plate'=>'车牌号'),$this->column);
        $header_column = [
            'id' => 'ID',
            'area' => '省/市/区',
            'order_sn' => '订单号',
            'member_id' => '用户UID',
            'user_phone' => '下单人手机号',
            'start_name' => '出发地点',
            'arrive_name' => '目的地点',
            'passenger_number' => '乘客数',
            'start_time' => '预约出发时间',
            'contact_number' => '联系人号码',
            'order_time' => '下单时间',
            'is_contract' => '是否包车',
            'order_price' => '订单金额',
            'driver_name' => '司机姓名',
            'driver_phone' => '司机手机号',
            'car_plate' => '车牌号',
            'fleet_name' => '归属车队',
            'order_status' => '订单状态',
            'is_pay' => '支付状态',
            'gifts_money'=> '抵扣金额',
            'coupon_price' => '优惠金额',
            'need_price' => '实付金额',
            'pay_time' => '支付时间',
            'driver_income' => '司机收入',
            'platform_price' => '平台费(包含车队收入)',
            'fleet_price' => '车队收入',
            'paytool' => '支付方式',
            'refund_money' => '实际退款金额',
            'driver_fine_money' => '司机罚款',
            'cancel_price' => '取消扣款',
        ];

        $header = array_merge(array('id' => 'ID', 'car_plate' => '车牌号'), $header_column);

        foreach ($res as $key => $value) {
            foreach ($header as $k => $v) {
                if (strpos($k, '_price') !== false || $k == 'user_money') {
                    $data[$key][$v] = number_format($value[$k], 2);
                    continue;
                }
                if ($k == 'journey' || $k == 'dis') {
                    $data[$key][$v] = number_format($value[$k] / 1000, 3);
                    continue;
                }
                $data[$key][$v] = $value[$k];
            }
        }
        Tools::excelExport('城际订单', $header, $data);
    }

    /**
     * 处理前端传来的参数
     * @param $data
     * @return  array
     * */
    private function dealInput($data)
    {
        $province_id = $data['province_id'];
        $city_id = $data['city_id'];
        $type = $data['type'];
        $start = strtotime($data['start']);
        $end = strtotime($data['end'] . ' 23:59:59');
        $order_status = $data['order_status'];
        $car_plate = trim($data['car_plate'], ' ');
        $type_phone = $data['type_phone'];
        $phone = trim($data['phone'], ' ');
        $pay_type = $data['pay_type'];
        $is_pay = $data['is_pay'];
        $fleet_id = $data['fleet_id'];
        $is_contract = $data['is_contract'];

        $order_sn = trim(input('get.order_sn'), ' ');
        $map = array();

        /*$base_condition = $this->base_condition;
        if($base_condition['inter'])$map['start_code'] = $base_condition['inter']['region_code'];*/
        switch ($type) {
            case 1:
                $key = 'order_time';
                break;
            case 2:
                $key = 'a.start_time';
                break;
            default:
                $key = '';
                break;
        }
        $data['start'] && $key && $map[$key] = array('egt', $start);
        $data['end'] && $key && $map[$key] = array('elt', $end);
        $data['start'] && $data['end'] && $key && $map[$key] = array('between', array($start, $end));
        $order_status != '' && $map['order_status'] = $order_status;
        $fleet_id && $map['fleet_id'] = $fleet_id;
        $is_contract && $map['is_contract'] = $is_contract;

        if ($province_id != '' && $city_id == '') {
            $region_code_res = Db::table('xm_region p')
                ->field('t.region_code')
                ->join(['xm_region' => 'c'], 'c.parent_id = p.region_id', 'LEFT')
                ->join(['xm_region' => 't'], 't.parent_id = c.region_id', 'LEFT')
                ->where('p.region_id', $province_id)->select();

            $region_code_data = '';
            foreach ($region_code_res as $key => $value) {
                $region_code_data .= $value['region_code'] . ',';
            }
            $map['start_code'] = ['in', rtrim($region_code_data, ',')];
        }

        if ($city_id != '') {
            $region_code_res = Db::table('xm_region c')
                ->field('t.region_code')
                ->join(['xm_region' => 't'], 't.parent_id = c.region_id', 'LEFT')
                ->where('c.region_id', $city_id)->select();

            $region_code_data = '';
            foreach ($region_code_res as $key => $value) {
                $region_code_data .= $value['region_code'] . ',';
            }
            $map['start_code'] = ['in', rtrim($region_code_data, ',')];
        }

        $is_pay != '' && $map['is_pay'] = $is_pay;

        $pay_type && $map['paytool'] = $pay_type;
        $order_sn && $map['order_sn'] = $order_sn;
        switch ($type_phone) {
            case 1:
                $phone_key = 'driver_phone';
                $data['phone'] && $phone_key && $map[$phone_key] = Security::encrypt($phone);
                break;
            case 2:
                $phone_key = 'user_phone';
                if ($phone) {
                    $user_logic = new UserLogic();
                    $map['a.member_id'] = $user_logic->getUserByPhone($phone, 'uid')['uid'];
                }
                break;
            default:
                $phone_key = '';
                break;
        }

        if ($car_plate) {
//			$where['car_plate'] = array('like',"%$car_plate%");
            $where['car_plate'] = Security::encrypt($car_plate);
            $car_ids = Db::table('xm_car_info')->where($where)->column('car_id');
            $map['a.car_id'] = array('in', $car_ids);
        }

        return $map;
    }

//    /**
//     * 查找可以分配订单的司机
//     * @param object
//     * @param $info
//     * @return array
//     * */
//    private function findAllotDriver($order_logic, $info)
//    {
//        $driver_logic = new DriverLogic();
//        $inter_driver_logic = new InterDriverLogic();
//        $start_local = explode(',', $info['start_local']);
////		$map_driver['is_goon']=array(array('eq',2),array('eq',3),'OR');
//        $map_driver['driver_status'] = 1;
//        $map_driver['auth_status'] = 1;
//        $map_driver['forbid'] = 2;
//        $map_driver['car_default'] = 1;
//        $map_driver['c.valid_time'] = ['>=', time()];   //判断行驶证是否过期
////        $map_driver['auth_type'] = 1; //司机认证类型 1 专车 2 出租车 3 私人运营车辆
//        $map_driver['driver_type'] = 2;
//
//        //归属车队
//        $map_driver['b.franchisee_type'] = 5; //1分公司 2区县代理 3驿站 4快车租赁公司 5城际车队
//        $map_driver['b.franchisee_id'] = $info['fleet_id'];
//
//        $driver_info = $driver_logic->getCarList($map_driver, 'a.car_id,a.driver_id,car_plate,seats,driver_name,b.franchisee_type,b.franchisee_id', $flag = true, $order = 'a.car_id desc', $page = 1, $limit = 99);
//
//        foreach ($driver_info as $key => $value) {
//            $driver_info[$key]['car_plate'] = Security::decrypt($value['car_plate']);
//        }
//
//        /******************************获取司机位置（mongo）***************************/
//        $map_driver_mongo['driverId'] = array('in', array_column($driver_info, 'a.driver_id'));
//        $map_driver_mongo['authType'] = 3;
//        $driver_coordinate = Db::connect(config('mongodb'))->table('live_driver_location')->where($map_driver_mongo)->field('driverId,location')->select();
//
//        $driver_coordinate = array_column($driver_coordinate, 'location', 'driverId');
//        /******************************获取司机位置（mongo）***************************/
//        $map_order_common['order_status'] = 35;//已分配
//        foreach ($driver_info as $key => $val) {
//            $map_order_common['a.driver_id'] = $val['driver_id'];
//
//            $order_logic = new OrderLogic();
//            $common_id_arr = $order_logic->getOrderCommon($map_order_common, 'a.id,a.banci_id');
//
//            $order_count = 0;
//            $flag = false;
//            foreach ($common_id_arr as $value) {
//                //$order_count += $order_logic->orderCountByCommonId($value['id']);
//                $order_count_res = Db::table('inter_order_common')->field('passenger_number')->where(['id' => $value['id']])->find();
//                $order_count += $order_count_res['passenger_number'];
//                //司机有分派订单，但是路线不一样，则不能被派单  2019-1-30注释  -张卫
//                // if($order_count && $value['banci_id']!=$info['banci_id']){
//                // 	unset($driver_info[$key]);$flag = true;
//                // 	break;
//                // }
//
//            }
//            /*************判断有订单的司机班线和本订单是否相同***********************/
//            if ($flag) {
//                continue;
//            }
//            /*************判断有订单的司机班线和本订单是否相同***********************/
//            /*************判断司机分配的乘客是否已满***********************/
//
//            //不限制 不同时间段 座位数
////			if($order_count>=$val['seats']){
////				unset($driver_info[$key]);
////				continue;
////			}
//
//            /*************判断司机分配的乘客是否已满***********************/
//
//            $work_area = $inter_driver_logic->getDriverByDid($val['driver_id'], 'a.driver_id');
//            $driver_info[$key]['work_area'] = $work_area['city'] . $work_area['county'];
//            if ($info['order_status'] == 30) {
//                $distance[$key] = Address::GetDistance($start_local[1], $start_local[0],
//                    $driver_coordinate[$val['driver']]['coordinates'][1], $driver_coordinate[$val['driver']]['coordinates'][0]) ?: 0;
//            }
//
//            $driver_info[$key]['allot_count'] = $order_count;
//        }
//
//        $distance ? asort($distance) : $distance = array();
//        return array('driver_info' => $driver_info, 'distance' => $distance);
//    }

    /**
     * 判断司机有无被分配订单并改变司机状态
     * @param $did
     * */
    private function dealDriverStatus($did)
    {
        $order_logic = new OrderLogic();
        $map['a.driver_id'] = $did;
        $map['a.order_status'] = 35;//已分配
        //       $common_id_arr = $order_logic->getOrderCommon($map,'id');
        $common_id_arr = $order_logic->getOrderCommon($map);
        $order_count = 0;
        foreach ($common_id_arr as $value) {
            $order_count += $order_logic->orderCountByCommonId($value['id']);
        }
        if (!$order_count) {
            $driver_logic = new DriverLogic();
            $driver_logic->renewDriver(array('driver_id' => $did), array('is_goon' => 2));
        }
    }

    /**
     * 变更订单司机关系的缓存
     * @param $did //司机id
     * @param $common_id //订单id
     * @param $type //1为增加，2为删除
     * */
    private function changeOrderDriverCache($did, $common_id, $type = 1)
    {
        $order_driver_cache = Cache::connect(config('inter_cache'))->get('order_driver_' . $did);
        switch ($type) {
            //增加
            case 1:
                $relation = array($common_id => 35);//司机派单
                if ($order_driver_cache) {
                    $relation = $relation + $order_driver_cache;
                }
                break;
            //取消派单
            case 2:
                if ($order_driver_cache) {
                    unset($order_driver_cache[$common_id]);
                    $relation = $order_driver_cache;
                }
                Cache::connect(config('inter_cache'))->rm('order_local_' . $common_id);
                break;
        }
        empty($relation) ? Cache::connect(config('inter_cache'))->rm('order_driver_' . $did) :
            Cache::connect(config('inter_cache'))->set('order_driver_' . $did, $relation, 0);
    }

    /**
     * 变更支付日志信息
     * @param $common_id //订单id
     * @param $did //司机id
     * @param $type //1为添加接单时间和经纬度，2为删除接单时间和经纬度
     * */
    private function dealPayLog($common_id, $did, $type)
    {
        switch ($type) {
            case 1:
                $driver = new DriverLogic();
                $driver_info = $driver->getInfoByDid($did, 'a.car_id,b.driver_id');
//                $driver_info = $driver->getInfoByDid($did,'a.car_id,b.driver_id,car_lng,car_lat');
                $data['order_time'] = time();
                //$data['order_local'] = $driver_info['car_lng'].','.$driver_info['car_lat'];
                $data['driver_id'] = $driver_info['driver_id'];
                $data['car_id'] = $driver_info['car_id'];
                break;
            case 2:
                $data['order_time'] = 0;
                $data['order_local'] = '';
                $data['driver_id'] = 0;
                $data['car_id'] = 0;
                break;
            default:
                break;
        }
        Db::table('xm_pay_log')->where('common_id', $common_id)->update($data);
    }

    /**
     * 添加派单操作日志信息
     * @param $common_id //订单id
     * @param $did //司机id
     * @param $type //1分配，2取消
     * */
    private function createAllotLog($common_id, $did, $type)
    {
        $order_logic = new OrderLogic();
        $car_logic = new CarLogic();
        $data['admin_id'] = session('admin_id');
        $data['driver_id'] = $did;
        $data['common_id'] = $common_id;
        $data['operate_type'] = $type;
        $data['operate_time'] = time();
        $start_local = explode(',', $order_logic->getOrderCommonById($common_id, 'start_local')['start_local']);
        $car_local = $car_logic->getCarInfoById($did, 'car_lat,car_lng', 2);
        $data['distance'] = Address::GetDistance($start_local[1], $start_local[0], $car_local['car_lat'], $car_local['car_lng']);
        Db::table('inter_allot_log')->insert($data);
    }

    /** * 更新城际订单后台通知信息
     * @param $common_id
     * */
    private function renewInterOrderMsg($common_id)
    {
        $res = Db::table('inter_order_message')->where('common_id', $common_id)->find();
        if ($res) {
            if (empty($res['admin_id'])) {
                $data['id'] = $res['id'];
                $data['admin_id'] = session('admin_id');
                $data['update_time'] = date('Y-m-d H:i:s');
                $data['is_deal'] = 1;
                Db::table('inter_order_message')->update($data);
            }

        }

    }

    /**
     * 线下支付列表
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function down_index()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        if ($page && $limit) {
            $is_real = empty(input('get.all_order'))?'':input('get.all_order');  //订单性质 1 普通订单 2 测试订单

            //非超级管理员
            $search = array();
            $search = $this->map_work_city;
            $search['a.is_del'] = 0;  //未删除

            //查询
            $data = input('get.');
            $start = strtotime($data['start']);
            $end = strtotime($data['end'] . ' 23:59:59');

            if($data['type'] == 1) { //下单时间
                $start && $search['a.add_time'] = array('egt', $start);
                $end && $search['a.add_time'] = array('elt', $end);
                $data['start'] && $data['end'] && $search['a.add_time'] = array('between', array($start, $end));
            } elseif($data['type'] == 2) { //支付时间
                $start && $search['a.pay_time'] = array('egt', $start);
                $end && $search['a.pay_time'] = array('elt', $end);
                $data['start'] && $data['end'] && $search['a.pay_time'] = array('between', array($start, $end));
            }

            if (input('get.order_sn')) {
                $search['order_sn'] = input('get.order_sn');
            }
            if (input('get.fleet_id')) {
                $search['franchisee_id'] = input('get.fleet_id');
            }
            if (input('get.order_status')) {
                $search['a.order_status'] = input('get.order_status');
            }
            if (input('get.user_phone')) {
                $search['a.passenger_phone'] = input('get.user_phone');
            }
            if (input('get.driver_name')) {
                $search['c.driver_name'] = input('get.driver_name');
            }
            if (input('get.car_plate')) {
                $search['d.car_plate'] = Security::decrypt(input('get.car_plate'));
            }

                $res = Db::table('inter_order_down a')->field('a.*,c.driver_name,c.franchisee_type,c.franchisee_id,c.driver_phone,d.car_plate')
                    ->join(['xm_driver_base' => 'c'], 'a.driver_id = c.driver_id', 'LEFT')
                    ->join(['xm_car_info' => 'd'], 'd.car_id = a.car_id', 'LEFT')
                    ->where($search)
                    ->where(function ($query) use ($is_real) {
                        $whiteList = Db::name('white_list')->order('id desc')->find();
                        if (!empty($is_real) && !empty($whiteList['driver_str'])) {
                            if ($is_real == 1) {            //普通订单
                                $query->where(['a.driver_id' => ['not in', $whiteList['driver_str']]]);
                            } elseif ($is_real == 2) {      //测试订单
                                $query->where(['a.driver_id' => ['in', $whiteList['driver_str']]]);
                            }
                        }
                    })
                    ->page($page, $limit)->order('a.down_id DESC')
                    ->select();

                $count = Db::table('inter_order_down a')->field('a.*,c.driver_name,c.franchisee_type,c.franchisee_id,d.car_plate')
                    ->join(['xm_driver_base' => 'c'], 'a.driver_id = c.driver_id', 'LEFT')
                    ->join(['xm_car_info' => 'd'], 'd.car_id = a.car_id', 'LEFT')
                    ->where($search)
                    ->where(function ($query) use ($is_real) {
                        $whiteList = Db::name('white_list')->order('id desc')->find();
                        if (!empty($is_real) && !empty($whiteList['driver_str'])) {
                            if ($is_real == 1) {            //普通订单
                                $query->where(['a.driver_id' => ['not in', $whiteList['driver_str']]]);
                            } elseif ($is_real == 2) {      //测试订单
                                $query->where(['a.driver_id' => ['in', $whiteList['driver_str']]]);
                            }
                        }
                    })
                    ->count();
//            }
            $whiteList = Db::name('white_list')->order('id desc')->find();
            foreach ($res as $key => $val) {
                $res[$key]['driver_phone'] = empty($val['driver_phone'])?'-':Security::decrypt($val['driver_phone']);
                //测试账号名单
                if (!empty($whiteList['driver_str']) && in_array($val['driver_id'], explode(',', $whiteList['driver_str']))) {
                    $res[$key]['driver_type'] = 1;
                } else {
                    $res[$key]['driver_type'] = 0;
                }

                $res[$key]['is_contract'] = $val['is_contract'] == 1 ? '<span style="color: #FF0000;">包车</span>' : '非包车';
                $res[$key]['money'] = empty($val['money'])?'-':number_format($val['money']/100, 2);
                $res[$key]['car_plate'] = empty($val['car_plate'])?'-':Security::decrypt($val['car_plate']);

                if($val['franchisee_type'] == 5 && $val['franchisee_id']) {
                    $fleet_res = Db::connect('db2')->table('fleet')->field('name')->where(['is_use'=>1, 'is_delete'=>0, 'id'=>$val['franchisee_id']])->find();
                    if($fleet_res) {
                        $res[$key]['fleet_name'] = $fleet_res['name'];
                    } else {
                        $res[$key]['fleet_name'] = '<span style="color: #FFB800">车队不存在</span>';
                    }
                } else {
                    $res[$key]['fleet_name'] = '<span style="color: #FF0000;">未归属车队</span>';
                }

                switch($val['order_status']) {
                    case 1 :
                        $res[$key]['order_status'] = '<span style="color: #1aad18;">待付款</span>';
                        break;
                    case 2 :
                        $res[$key]['order_status'] = '已付款';
                        break;
                    case 3 :
                        $res[$key]['order_status'] = '<span style="color: #ff0000;">已取消</span>';
                        break;
                    default:;
                }
                $res[$key]['add_time'] = empty($val['add_time'])?'':date('Y-m-d H:i:s',$val['add_time']);
                $res[$key]['pay_time'] = empty($val['pay_time'])?'':date('Y-m-d H:i:s',$val['pay_time']);
            }

            echo json_encode(array(
                'code' => 0,
                'msg' => '',
                'limit' => $limit,
                'count' => $count,
                'data' => $res
            ));
            exit;
        } else {
            $fleet_list = Db::connect('db2')->table('fleet')->field('id,name')->where(['is_use'=>1,'is_delete'=>0])->select();

            $order_status = [
                1 => '待付款',
                2 => '已付款',
                3 => '已取消'
            ];

            //App显示开关
            $status = Db::table('xm_config')->field('id,value')->where(['name'=>'interOrderDownSwitch','inc_type'=>'interOrderDown'])->find();
            if($status) {
                $this->assign('status',$status['value']);
            }

            $this->assign('order_status',$order_status);
            $this->assign('fleet_list',$fleet_list);
            return $this->fetch();
        }

    }

    //导出数据
    public function down_excel()
    {
        $all = input('get.all');
        $page = input('get.page') ?: 1;
        $limit = $all == 1 ? 1000 : input('get.limit');

        $is_real = empty(input('get.all_order'))?'':input('get.all_order');  //订单性质 1 普通订单 2 测试订单

        //非超级管理员
        $search = array();
        $search['a.is_del'] = 0;  //未删除

        //查询
        $data = input('get.');
        $start = strtotime($data['start']);
        $end = strtotime($data['end'] . ' 23:59:59');

        if($data['type'] == 1) { //下单时间
            $start && $search['a.add_time'] = array('egt', $start);
            $end && $search['a.add_time'] = array('elt', $end);
            $data['start'] && $data['end'] && $search['a.add_time'] = array('between', array($start, $end));
        } elseif($data['type'] == 2) { //支付时间
            $start && $search['a.pay_time'] = array('egt', $start);
            $end && $search['a.pay_time'] = array('elt', $end);
            $data['start'] && $data['end'] && $search['a.pay_time'] = array('between', array($start, $end));
        }

        if (input('get.fleet_id')) {
            $search['franchisee_id'] = input('get.fleet_id');
        }
        if (input('get.order_status')) {
            $search['a.order_status'] = input('get.order_status');
        }
        if (input('get.user_phone')) {
            $search['a.passenger_phone'] = input('get.user_phone');
        }
        if (input('get.driver_name')) {
            $search['c.driver_name'] = input('get.driver_name');
        }
        if (input('get.car_plate')) {
            $search['d.car_plate'] = Security::decrypt(input('get.car_plate'));
        }

        $res = Db::table('inter_order_down a')->field('a.*,c.driver_name,c.franchisee_type,c.franchisee_id,c.driver_phone,d.car_plate')
            ->join(['xm_driver_base' => 'c'], 'a.driver_id = c.driver_id', 'LEFT')
            ->join(['xm_car_info' => 'd'], 'd.car_id = a.car_id', 'LEFT')
            ->where($search)
            ->where(function ($query) use ($is_real) {
                $whiteList = Db::name('white_list')->order('id desc')->find();
                if (!empty($is_real) && !empty($whiteList['driver_str'])) {
                    if ($is_real == 1) {            //普通订单
                        $query->where(['a.driver_id' => ['not in', $whiteList['driver_str']]]);
                    } elseif ($is_real == 2) {      //测试订单
                        $query->where(['a.driver_id' => ['in', $whiteList['driver_str']]]);
                    }
                }
            })
            ->page($page, $limit)->order('a.down_id DESC')
            ->select();

        $whiteList = Db::name('white_list')->order('id desc')->find();
        foreach ($res as $key => $val) {
            $res[$key]['driver_phone'] = empty($val['driver_phone'])?'-':Security::decrypt($val['driver_phone']);
            //测试账号名单
            if (!empty($whiteList['driver_str']) && in_array($val['driver_id'], explode(',', $whiteList['driver_str']))) {
                $res[$key]['driver_type'] = 1;
            } else {
                $res[$key]['driver_type'] = 0;
            }

            $res[$key]['is_contract'] = $val['is_contract'] == 1 ? '包车' : '非包车';
            $res[$key]['money'] = empty($val['money'])?'-':number_format($val['money']/100, 2);
            $res[$key]['car_plate'] = empty($val['car_plate'])?'-':Security::decrypt($val['car_plate']);

            if($val['franchisee_type'] == 5 && $val['franchisee_id']) {
                $fleet_res = Db::connect('db2')->table('fleet')->field('name')->where(['is_use'=>1, 'is_delete'=>0, 'id'=>$val['franchisee_id']])->find();
                if($fleet_res) {
                    $res[$key]['fleet_name'] = $fleet_res['name'];
                } else {
                    $res[$key]['fleet_name'] = '车队不存在';
                }
            } else {
                $res[$key]['fleet_name'] = '未归属车队';
            }

            switch($val['order_status']) {
                case 1 :
                    $res[$key]['order_status'] = '待付款';
                    break;
                case 2 :
                    $res[$key]['order_status'] = '已付款';
                    break;
                case 3 :
                    $res[$key]['order_status'] = '已取消';
                    break;
                default:;
            }
            $res[$key]['add_time'] = empty($val['add_time'])?'':date('Y-m-d H:i:s',$val['add_time']);
            $res[$key]['pay_time'] = empty($val['pay_time'])?'':date('Y-m-d H:i:s',$val['pay_time']);
        }

        $header = [
            'down_id' => 'ID',
            'order_sn' => '订单号',
            'start_name' => '出发地',
            'arrive_name' => '目的地',
            'is_contract' => '是否包车',
            'passenger_number' => '乘客数',
            'passenger_phone' => '乘客手机号',
            'money' => '车费(元)',
            'add_time' => '下单时间',
            'pay_time' => '支付时间',
            'driver_name' => '司机姓名',
            'driver_phone' => '司机手机号',
            'car_plate' => '车牌号',
            'fleet_name' => '所属车队',
            'order_status' => '订单状态',
        ];

        $data_res = [];
        foreach ($res as $key => $value) {
            foreach ($header as $k => $v) {
                $data_res[$key][$v] = $value[$k];
            }
        }
        Tools::excelExport('城际下线订单', $header, $data_res);
    }

//    //取消
//    public function down_cancel()
//    {
//        $data['status'] = input('post.status')?input('post.status'):0;
//
//        //查询 配置文件是否配置 线下行程是否显示开关 1显示0不显示
//        $config_info = Db::table('xm_config')->field('id,value')->where(['name'=>'interOrderDownSwitch', 'inc_type'=>'interOrderDown'])->find();
//
//        if($config_info) {
//            Db::table('xm_config')->where(['id'=>$config_info['id']])->update(['value'=>$data['status']]);
//        } else {
//            return json(array('status' => 0, 'msg' => '配置文件尚未配置'));
//        }
//        return json(array('status' => 1, 'msg' => '操作成功'));
//    }

    /**
     * 线下支付详情
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function down_detail()
    {
        $down_id = input('get.down_id');

        $info = Db::table('inter_order_down a')
            ->field('a.*,c.driver_name,c.driver_phone,c.franchisee_type,c.franchisee_id,d.car_plate,d.color,d.car_brand,d.car_model')
            ->join(['xm_driver_base' => 'c'], 'a.driver_id = c.driver_id', 'LEFT')
            ->join(['xm_car_info' => 'd'], 'd.car_id = a.car_id', 'LEFT')
            ->where('down_id', $down_id)
            ->find();

        switch($info['order_status']) {
            case 1 :
                $info['order_status'] = '<span style="color: #1aad18;">待付款</span>';
                break;
            case 2 :
                $info['order_status'] = '已付款';
                break;
            case 3 :
                $info['order_status'] = '<span style="color: #ff0000;">已取消</span>';
                break;
            default:;
        }
        $info['is_contract'] = $info['is_contract'] == 1 ? '<span style="color: #FF0000;">包车</span>' : '非包车';
        $info['driver_phone'] = Security::decrypt($info['driver_phone']);

        $info['car_plate'] = Security::decrypt($info['car_plate']);
        $info['color'] = Security::decrypt($info['color']);
        $info['car_brand'] = Security::decrypt($info['car_brand']);
        $info['car_model'] = Security::decrypt($info['car_model']);
        $info['car_info'] = $info['color'].'-'.$info['car_model'];
        $info['add_time'] = empty($info['add_time'])?'':date('Y-m-d H:i:s', $info['add_time']);
        $info['pay_time'] = empty($info['pay_time'])?'':date('Y-m-d H:i:s', $info['pay_time']);

        if($info['franchisee_type'] == 5 && $info['franchisee_id']) {
            $fleet_res = Db::connect('db2')->table('fleet')->field('name')->where(['is_use'=>1, 'is_delete'=>0, 'id'=>$info['franchisee_id']])->find();
            if($fleet_res) {
                $info['fleet_name'] = $fleet_res['name'];
            } else {
                $info['fleet_name'] = '<span style="color: #FFB800">车队不存在</span>';
            }
        } else {
            $info['fleet_name'] = '<span style="color: #FF0000;">未归属车队</span>';
        }
        $payLog = Db::table('xm_pay_log a')
            ->field('a.*')
            ->where(['common_id'=>$down_id, 'order_type'=>5])
            ->order("log_id desc")
            ->find();
        if($payLog){
            $info['paytool']=$payLog['pay_type'];
        }

        switch($info['paytool']) {
            case 1:
                $info['paytool'] = '支付宝';
                break;
            case 2:
                $info['paytool'] = '微信';
                break;
            default:
                $info['paytool'] = '-';
        }

        $data['info'] = decode_array_inter($info);
        $data['info'] = $info;
        $info['longitude'] = explode(',',$info['pay_location'])[0];
        $info['latitude'] = explode(',',$info['pay_location'])[1];
        $res = get_info_by_local($info['longitude'] . ',' . $info['latitude']);
        $res_url = json_decode($res, true);
        $data['pay_address'] = empty($res_url['regeocode']['formatted_address'])?'':$res_url['regeocode']['formatted_address'];

        $this->assign('data', $data);
        return view();
    }

    public function getCityList()
    {
        $province_id = input('post.province_id');
        $html = '';
        if ($province_id) {
            $city_list = Db::table('xm_region')->field('region_id,region_name')->where('parent_id', $province_id)->select();

            foreach ($city_list as $key => $value) {
                $html .= "<option value='" . $value['region_id'] . "'>" . $value['region_name'] . "</option>";
            }
        }
        echo $html;
    }

    /**
     * 订单数据
     */
    public function tableData()
    {
        //$fleet_list = Db::connect('db2')->table('fleet')->order('id DESC')->select();
//        $fleet_list = Db::connect('db2')->table('fleet')->field('id,name')->order('id DESC')->select();
        $config['fleet_list'] = null;
        $config['is_contract'] = ['否', '是'];
        $res = [];
        $data = input('post.');
        $all_order=$data['all_order'];
//        $fleet_list = Db::connect('db2')->table('fleet')->order('id DESC')->select();
        $fWhere=' and b.is_del=2 ';
        if (!$data['start_time']) {
            //$fWhere['order_time'] = ['between', [strtotime('-1 week'), strtotime('now')]];//订单筛选条件
            $fWhere .= " and b.order_time between '".strtotime('-1 week')."' and '".strtotime('now')."'";
            $sWhere['a.create_time'] = ['between', [strtotime('-1 week'), strtotime('now')]];//business筛选
        } else {
            //$fWhere['order_time'] = ['between', [strtotime($data['start_time'] . "00:00:00"), strtotime($data['end_time'] . " 23:59:59")]];//订单筛选条件
            $fWhere .= " and b.order_time between '".strtotime($data['start_time'] . '00:00:00')."' and '".strtotime($data['end_time'] . '23:59:59')."'";
            $sWhere['a.create_time'] = ['between', [strtotime($data['start_time'] . "00:00:00"), strtotime($data['end_time'] . " 23:59:59")]];//business筛选
        }

        if ($data) {
            if (!empty($data['city'])) {
                $whereRegion = ['work_city'=>['=', $data['city']]];
            }else{
                $whereRegion=[];
            }
            if (!empty($data['fleet_id'])) {
                $whereFleet = ['franchisee_id'=>['=', $data['fleet_id']]];
            }else{
                $whereFleet = ['franchisee_id'=>['not null']];
            }
            //查询司机ID
                $did = Db::name('driver_base')->where($whereFleet)->field('driver_id')->where('driver_id', 'in', function ($query) use ($whereRegion) {
                    $query->table('xm_driver_info')->where($whereRegion)->field('driver_id');
                })->select();

            $whereOrderW = [];
            //查询设置 - 测试账号信息
            $whiteList = Db::name('white_list')->order('id desc')->find();
            if (!empty($all_order) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))) {
                if ($all_order == 1) {
                    //$whereOrderW['member_id'] = ['not in', $whiteList['uid_str']];
                    //$whereOrderW['driver_id'] = ['not in', $whiteList['driver_str']];      //普通订单

                    $fWhere .=' and member_id not in('.$whiteList['uid_str'].') ';
                    $fWhere .=' and driver_id not in('.$whiteList['driver_str'].') ';
                } elseif ($all_order == 2) {
                    $whereOrderW['member_id'] = ['in', $whiteList['uid_str']];
                    $whereOrderW['driver_id'] = ['in', $whiteList['driver_str']];          //测试订单

                    $fWhere .=' and member_id in('.$whiteList['uid_str'].') ';
                    $fWhere .=' and driver_id in('.$whiteList['driver_str'].') ';
                }
            }
            $whereOrderW['is_del'] = 2;

            /*foreach ($did as $key => $value) {
                $res['allMoney'] += Db::table('inter_order_common')->where('driver_id','=',$value['driver_id'])->where('order_status','in', [45,47,50])->where($fWhere)->where($whereOrderW)->value('SUM(order_price)');
                //$res['sumOrderNumStr'] += Db::table('inter_order_common')->where('driver_id','=',$value['driver_id'])->where('order_status','in', [45,47,50])->where($whereOrderW)->where('order_time', 'between', [strtotime(date("Y-m-d")), strtotime(date("Y-m-d 23:59:59"))])->count();
                $res['actualMoney'] += Db::table('inter_order_common')->where('driver_id','=',$value['driver_id'])->where('order_status','in', [45,47,50])->where($whereOrderW)->where($fWhere)->value('SUM(need_price)');
                $res['platform_price'] += Db::table('inter_order_common')->where('driver_id','=',$value['driver_id'])->where('order_status','in', [45,47,50])->where($whereOrderW)->where($fWhere)->value('SUM(platform_price)') ;
                $res['coupon_price'] += Db::table('inter_order_common')->where('driver_id','=',$value['driver_id'])->where('order_status','in', [45,47,50])->where($whereOrderW)->where($fWhere)->value('SUM(coupon_price)');
            }*/

            $fleet_list_id = array_column($did,'driver_id');
            $fleet_list_id = implode(",", $fleet_list_id);
            $sql="SELECT COALESCE(SUM(b.order_price),0) as allMoney, COALESCE(SUM(b.need_price),0) as actualMoney, COALESCE(SUM(b.platform_price),0) as platform_price, COALESCE(SUM(b.coupon_price),0) as coupon_price FROM inter_order_common AS b WHERE b.driver_id in (".$fleet_list_id.") AND b.order_status in(45,47,50)".$fWhere;

            $orderInfo = Db::query($sql);

            $res['allMoney']=$orderInfo[0]['allMoney'];
            $res['actualMoney']=$orderInfo[0]['actualMoney'];
            $res['platform_price']=$orderInfo[0]['platform_price'];
            $res['coupon_price']=$orderInfo[0]['coupon_price'];

        } else {
            $whereOrderW['is_del'] = 2;
            $fleet_list_id = array_column($fleet_list,'id');
            $fleet_list_id = implode(",", $fleet_list_id);
            $sql="SELECT COALESCE(SUM(b.order_price),0) as allMoney, COALESCE(SUM(b.need_price),0) as actualMoney, COALESCE(SUM(b.platform_price),0) as platform_price, COALESCE(SUM(b.coupon_price),0) as coupon_price FROM inter_order_common AS b WHERE b.driver_id in ( SELECT driver_id FROM xm_driver_base WHERE franchisee_id in(".$fleet_list_id.") )AND b.order_status in(45,47,50)".$fWhere;

            $orderInfo = Db::query($sql);

            $res['allMoney']=$orderInfo['allMoney'];
            $res['actualMoney']=$orderInfo['actualMoney'];
            $res['platform_price']=$orderInfo['platform_price'];
            $res['coupon_price']=$orderInfo['coupon_price'];

            /*foreach ($fleet_list as $k => $v) {
                $did = Db::name('driver_base')->where('franchisee_id', 'in', $v['id'])->value('driver_id');
                $res['allMoney'] += Db::table('inter_order_common')->where(['driver_id' => ['in', $did], 'order_status' => ['in', [45,47,50]]])->where($fWhere)->where($whereOrderW)->value('SUM(order_price)');
                //$res['allMoney'] += Db::table('inter_order_common')->where(['order_status' => ['in', [45,47,50]]])->where($fWhere)->where($whereOrderW)->value('SUM(order_price)');
                //$res['sumOrderNumStr'] += Db::table('inter_order_common')->where(['driver_id' => ['in', $did], 'order_status' => ['in', [45,47,50]]])->where($whereOrderW)->where('order_time', 'between', [strtotime(date("Y-m-d")), strtotime(date("Y-m-d 23:59:59"))])->count();
                $res['actualMoney'] += Db::table('inter_order_common')->where(['driver_id' => ['in', $did], 'order_status' => ['in', [45,47,50]]])->where($fWhere)->where($whereOrderW)->value('SUM(need_price)');
                $res['platform_price'] += Db::table('inter_order_common')->where(['driver_id' => ['in', $did], 'order_status' => ['in', [45,47,50]]])->where($whereOrderW)->where($fWhere)->value('SUM(platform_price)');
                $res['coupon_price'] += Db::table('inter_order_common')->where(['driver_id' => ['in', $did], 'order_status' => ['in', [45,47,50]]])->where($whereOrderW)->where($fWhere)->value('SUM(coupon_price)');
            }*/
        }

        foreach ($fleet_list as $k => $v) {
            $res['driver_num'] += Db::name('driver_base')->where('franchisee_id', 'in', $v['id'])->count();
        }
//24小时订单数据量（只是今天）
        $dateArrOrder = [];
        $start_time = !empty($data['start_time']) ? strtotime($data['start_time']) : strtotime(date("Y-m-d"));
        $end_time = !empty($data['end_time']) ? strtotime($data['end_time']) : strtotime(date("Y-m-d 23:59:59"));
        /*while ($start_time <= $end_time) {
            $dateArrOrder[] = date('Y-m-d', $start_time);
            $start_time = strtotime('+1 day', $start_time);
        }*/
//查询省市区
        $region_model = new RegionModel();
//查询获取省份
        $where = [
            'parent_id' => 1,
            'region_level' => 1
        ];

        $config['province'] = $region_model->getRegion($where, 'region_id,region_name');
        $res['sumOrderInfo'] = OrderCommonModel::totalOrderNumber($dateArrOrder,$data['all_order']);
        $res['allMoney'] = sprintf('%.2f', $res['allMoney']);
        $res['driverMoney'] = sprintf('%.2f', $res['allMoney'] * 0.9);
        $res['actualMoney'] = sprintf('%.2f', $res['actualMoney']);
        $res['platform_price'] = sprintf('%.2f', $res['platform_price']);
        $res['coupon_price'] = sprintf('%.2f', $res['coupon_price']);
        $res['business'] = sprintf('%.2f', db('business_log a')->field('a.id,a.order_sn,a.first_money,a.percent_money,a.create_time,a.state,a.type,b.name,c.user_phone')
            ->join('business b', 'a.business_id=b.id', 'LEFT')
            ->join('user c', 'a.uid=c.uid', 'LEFT')
            ->order('a.id desc')->where($sWhere)->value('SUM(first_money)'));

        $this->assign($res);
        $cityName = Db::table('xm_region')->field('region_id,region_name')->where('region_id', $data['city'])->find();
        if ($cityName){
            $this->assign('cityName',$cityName);
        }

        $this->assign('data',$data);
        $this->assign($config);
        return $this->fetch();
    }
    public function imgData(){
        $orderModel=new OrderCommonModel();
        $fleet_id=input('post.fleet_id');
        $start_time = input('post.start_time');
        $end_time   = input('post.end_time');
        $type       = input('post.type')?input('post.type'):'column';
        $all_order  = input('post.all_order');
        if(!empty($start_time) && $end_time){
            $this->assign('start_time',$start_time);
            $this->assign('end_time',$end_time);
            $start_time =  strtotime($start_time);
            $end_time   =  strtotime($end_time);
            while ($start_time <= $end_time){
                $dateArray[] = date('Y-m-d',$start_time);
                $start_time = strtotime('+1 day',$start_time);
            }
        }else{
            if(!empty($start_time) && empty($end_time)){
                return "<script type='application/javascript'>alert('结束日期不能为空');parent.window.location.reload();</script>";die;
            }
            $curtime = !empty($end_time)?$end_time:time();
            $day=7;//因为统计七天数据
            for ($i=0;$i<$day;$i++){
                $dateArray[] = date('Y-m-d',$curtime-$i*24*60*60);
            }
        }
        for($i = 0 ; $i <= 23 ; $i++){
            if(strlen($i) == 1){
                $timeArr[] = '0'.$i.":00";
            }else{
                $timeArr[] = $i.":00";
            }
        }
        sort($dateArray);
        $result = $orderModel->totalInfo($dateArray,$all_order,$fleet_id);
        //查询时间段订单数量
        $sumOrderNumStr = $orderModel->timeOrderNum($dateArray,$all_order,$fleet_id);
        $this->assign('dateArray',$dateArray);
        $this->assign('result',$result);
        $this->assign('all_order',$all_order);
        $this->assign('type',$type);
        $this->assign('timeArr',$timeArr);
        $this->assign('sumOrderNumStr',$sumOrderNumStr);
        $fleetList = Db::connect('db2')->table('fleet')->field('id,name')->order('id DESC')->select();
        $carRoute=Db::table('inter_car_route')->order('id DESC')->select();
        $config['fleet_list'] = $fleetList;
        $config['route_list'] = $carRoute;
        $this->assign('fleet_id',$fleet_id);

        $this->assign($config);
        return $this->fetch();
    }

    public function sound() {
        $common_id = input('get.common_id');
        $order_type = input('get.order_type'); // 1快车  3城际 4顺风车

        if(empty($common_id) || !in_array($order_type,[1,3,4])) {
            return "<script type='application/javascript'>alert('参数错误！');window.history.back();</script>";
        }

        //请求 java 接口
        $java_url = Env::get('javaPush'.ENV.'_host') ."/thirdParty/getSecretRecordDownloadUrl";

        $post_data = [];
        $post_data['commonId'] = $common_id;
        $post_data['orderType'] = intval($order_type);

        //curl请求
        $res = https_request($java_url, $post_data);
        $res_data = json_decode($res,true);

        if ($res_data['status'] == 200) {
            $sound_info = [];
            foreach($res_data['data'] as $key => $value) {
                $sound_info[$value['callTimeStr']] = $value['downloadUrl'];
            }
        } else {
            $sound_info = ""; //暂无数据
        }
        $this->assign('sound_info',$sound_info);

        return $this->fetch();
    }

}
